<template>
  <div>
    <div
      style="height: calc(55vh - 3.5rem)"
      class="overflow-y-auto"
      :infinite-scroll-immediate="false"
      :infinite-scroll-distance="50"
      v-infinite-scroll="loadMore"
      v-if="tableData && tableData.length > 0"
    >
      <el-card
        v-for="item in tableData"
        :key="item.id"
        class="card_item"
        :class="{
          change_card_item: checkDetailForm.id == item.id,
        }"
        @click="handleChangeCheck(item.id)"
      >
        <div class="code">{{ item.code || "" }}</div>
        <div class="content">
          <el-avatar
            class="mr-2"
            :size="40"
            src="https://file.supore.cn/1751784079boy.png"
            v-if="item.sex == 1"
          />
          <el-avatar
            class="mr-2"
            :size="40"
            src="https://file.supore.cn/1751784096girl.png"
            v-else-if="item.sex == 2"
          />
          <el-avatar
            class="mr-2"
            :size="40"
            src="https://file.supore.cn/1746599689male.jpg"
            v-else
          />

          <div class="info">
            <el-text truncated class="text-[0.8rem] text-[white]">
              {{ item.relationName || "" }}
            </el-text>
            <div class="relation_phone mt-[0.2rem]">
              {{ item.phone || item.customerPhone || "" }}
            </div>
          </div>
        </div>
        <div class="time">{{ item.createdAt || "" }}</div>
      </el-card>
    </div>

    <el-empty description="暂无检查" :image-size="160"></el-empty>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";
import { handleApiResponse } from "@/utils/request.js";
import { QueryChecklistInfoById } from "../../../../../wailsjs/go/api/ReportApi.js";
import { ListCustomerChecklistInfos } from "../../../../../wailsjs/go/api/CustomerApi.js";
import {
  ConnectToSSE,
  StopSSE,
} from "../../../../../wailsjs/go/api/CustomerApi.js";

onMounted(() => {
  getList();
});

const emit = defineEmits(["handleBack"]);
const props = defineProps({
  code: {
    type: String,
    default: "",
  },
  timeType: {
    type: Number,
    default: 1,
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const userStore = useUserStore();
const { checkDetailForm } = storeToRefs(userStore);
// 点击选中单个检查单
const handleChangeCheck = (id) => {
  handleApiResponse(() => QueryChecklistInfoById(id)).then((res) => {
    if (res.code == 0) {
      // console.log(res);
      let form = {};
      form.id = res.data.id;
      form.code = res.data.code;
      form.relationId = res.data.relationId || null;
      form.relationName = res.data.relationName || "";
      form.relationPhone = res.data.relationPhone || "";
      form.phone = res.data.phone || "";
      form.baseRelationName = res.data.baseRelationName || "";
      form.customerId = res.data.customerId || null;
      form.customerPhone = res.data.customerPhone || "";
      form.customerTel = res.data.customerPhone || "";
      form.customerName = res.data.customerName || "";
      form.customerId = res.data.customerId || null;
      form.sex = res.data.sex || null;
      form.age = res.data.age || null;
      form.birthday = res.data.birthday || null;
      form.createdAt = res.data.createdAt || "";
      form.medicalCardNumber = res.data.medicalCardNumber || "";
      form.occupation = res.data.occupation || "";
      form.eyeDistance = res.data.eyeDistance || "";
      form.workEnvironment = res.data.workEnvironment || "";
      form.complaints = res.data.complaints || "";
      form.projectList = res.data.projectList
        ? res.data.projectList.sort((a, b) => a.regionId - b.regionId)
        : [];
      form.projectList.forEach((item) => {
        item.isChecked = true;
      });
      userStore.updateCheckDetailForm(form);
      userStore.updateFlowActiveIndex(2);
      userStore.updateCutStatus(2);

      setStorageWithEvent("refresh_region_item");
      setStorageWithEvent("change_checkDetailForm");
    }
  });
};

const page = ref(1);
const size = ref(10);
const total = ref(0);
const code = ref("");
const timeType = ref(1);
const tableData = ref([]);
// 获取检查单列表
const getList = (val) => {
  if (val) {
    code.value = val.code;
    timeType.value = val.checkTimeId;
  }
  emit("handleBack", true);
  handleApiResponse(() =>
    ListCustomerChecklistInfos({
      page: page.value,
      size: size.value,
      code: code.value,
      timeType: timeType.value,
      ...val,
    })
  ).then((res) => {
    if (res.code == 0) {
      tableData.value = res.data.list || [];
      total.value = res.data.total || 0;
    }
    emit("handleBack", false);
  });
};

// 滚动加载更多
const loadMore = () => {
  if (size.value < total.value) {
    size.value += 10;
    getList();
  }
};

// 监听一键生成检查单后，列表也随之刷新
let cleanup;
onMounted(() => {
  cleanup = watchStorage("refresh_checkList", (newValue) => {
    getList();
  });

  // 组件卸载时清理监听
  return () => cleanup();
});

onBeforeUnmount(() => {
  cleanup();
});

defineExpose({
  getList,
});
</script>

<style scoped lang="scss">
.card_item {
  @apply w-full bg-[#ccc] text-[0.65rem] mt-[0.2rem];
  &:hover {
    @apply bg-[var(--theme-color)] cursor-pointer;
  }

  .code {
    @apply text-right text-[#800000];
  }

  .content {
    @apply w-full h-[2.5rem] flex items-center;
    .info {
      @apply w-[50%] h-[2.2rem] mt-[0.3rem] text-[white];
    }
  }

  .time {
    @apply text-right text-[black];
  }
}
.change_card_item {
  @apply bg-[var(--theme-color)];
}
</style>